# -*- coding:utf-8 -*-
from tornado import gen
import random
import StringIO
import xlwt

from common import utiltool, timetool
from appcommon.framework import BaseHandler


class TimeListHandler(BaseHandler):
    """
    橙子用，时间列表
    """
    # @decorator.check_params(['product_type', 'class_id', 'site_id'])
    # @decorator.verify_params
    @gen.coroutine
    def get(self):
        start_str = self.get_argument('start', '')
        end_str = self.get_argument('end', '')
        # cnt = int(self.get_argument('cnt', '500'))
        ngte = int(self.get_argument('ngte', ''))
        nlte = int(self.get_argument('nlte', ''))
        start = timetool.convert_date_to_timestamp(start_str)
        end = timetool.convert_date_to_timestamp(end_str)
        timestamp_list = []
        current = start
        while current <= end:
            tmp = random.randint(nlte, ngte)
            current = current+tmp
            if current <= end:
                timestamp_list.append(current)
        # out = len(timestamp_list) - cnt
        # while out > 0:
        #     i = random.randint(1, len(timestamp_list)-2)
        #     if timestamp_list[i+1] - timestamp_list[i-1] <= ngte:
        #         timestamp_list.remove(timestamp_list[i])
        #         out = len(timestamp_list) - cnt
        #     else:
        #         for j in range(i, i + 20):
        #             if j < len(timestamp_list)-2:
        #                 if timestamp_list[j + 1] - timestamp_list[j - 1] <= ngte:
        #                     timestamp_list.remove(timestamp_list[j])
        #                     out = len(timestamp_list) - cnt

        res = []
        for item in timestamp_list:
            res.append(timetool.convert_timestamp_to_date(item))

        s = StringIO.StringIO()
        f = xlwt.Workbook()  # 创建工作簿
        '''
         创建第一个sheet:
          sheet1
        '''
        sheet1 = f.add_sheet(u'sheet1', cell_overwrite_ok=True)  # 创建sheet
        row0 = [u'时间']

        # 生成第一行
        for i in range(0, len(row0)):
            sheet1.write(0, i, row0[i])
        for i in range(0, len(res)):
            sheet1.write(i + 1, 0, res[i])

        f.save(s)  # 保存文件
        s.seek(0)

        filename = start_str.replace('-', '').replace(':', '').replace(' ', '') \
                   + '-' + end_str.replace('-', '').replace(':', '').replace(' ', '') \
                   + "-" +str(len(res))+ ".xls"
        self.set_header('Content-Type', 'application/octet-stream')
        self.set_header('Content-Disposition', 'attachment; filename=' + filename)
        buf_size = 4096
        while True:
            data = s.read(buf_size)
            if not data:
                break
            self.write(data)
        self.finish()
